<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert title="添加商品信息" center type="info" show-icon></el-alert>
            <el-steps :active="active-0" finish-status="success" align-center style="margin-top: 20px">
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
            </el-steps>
            <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-position="top">
                <el-tabs v-model="active" tab-position="left" :before-leave="beforeTabLeave" @tab-click="tabClick">
                    <el-tab-pane name="0" label="基本信息">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="addForm.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="addForm.goods_weight" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="addForm.goods_number" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader v-model="addForm.goods_cat" :options="options" @change="handleChange" :props="prop"></el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane name="1" label="商品参数">
<!--                        渲染表单的item项-->
                        <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox border :label="cb" v-for="(cb,i) in item.attr_vals" :key="i"></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane name="2" label="商品属性">
                        <el-form-item v-for="item in onlyTableData" :key="item.attr_id" :label="item.attr_name">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane name="3" label="商品图片">
<!--                        action表示图片要上传到的api-->
                        <el-upload
                                :action="upLoadUrl"
                                :on-preview="handlePreview"
                                :on-remove="handleRemove"
                                list-type="picture"
                                :headers="headerObj"
                                :on-success="handleSuccess">
                            <el-button size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane name="4" label="商品内容">
<!--                        富文本编辑器组件-->
                        <quill-editor v-model="addForm.goods_introduce">
                        </quill-editor>
                        <el-button type="primary" class="btn_add" @click="add">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
        <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
            <img :src="previewPath" alt="" class="previewImg">
        </el-dialog>
    </div>
</template>

<script>
    import _ from 'lodash'
    export default {
        name: "add",
        data(){
            return{
                active:'0',
                addForm:{
                    goods_name:'',
                    goods_price:0,
                    goods_weight:0,
                    goods_number:0,
                    goods_cat:[],
                    //图片的数组
                    pics:[],
                    //商品的详情描述
                    goods_introduce:'',
                    attrs:[]
                },
                addFormRules:{
                    goods_name:[{required:true,message:'请输入商品名称',trigger:'blur'}],
                    goods_price:[{required:true,message:'请输入商品价格',trigger:'blur'}],
                    goods_weight:[{required:true,message:'请输入商品重量',trigger:'blur'}],
                    goods_number:[{required:true,message:'请输入商品数量',trigger:'blur'}],
                    goods_cat:[{required:true,message:'请选择商品分类',trigger:'blur'}],
                },
                options:[],
                prop:{
                    expandTrigger:'hover',
                    value:'cat_id',
                    label:'cat_name'
                },
                cat_id:0,
                manyTableData:[],
                onlyTableData:[],
                //上传图片的url
                upLoadUrl:'http://120.27.246.168:8888/api/private/v1/upload',
                headerObj:{
                    Authorization:window.sessionStorage.getItem('token')
                },
                previewPath:'',
                previewVisible:false
            }
        },
        created() {
          this.getCateList()  
        },
        computed:{
          price(){
              return this.addForm.goods_price
          },
          weight(){
              return this.addForm.goods_weight
          },
          number(){
              return this.addForm.goods_number
          }  
        },
        watch:{
            price(newval){
                this.addForm.goods_price=newval<0?0:newval
            },
            weight(newval){
                this.addForm.goods_weight=newval<0?0:newval
            },
            number(newval){
                this.addForm.goods_number=newval<0?0:newval
            }
        },
        methods:{
            //获取商品分类
            getCateList(){
                this.$http.get('categories').then((res=>{
                    if (res.data.meta.status==200){
                      this.options = res.data.data
                    }
                }))
            },
            handleChange(){

            },
            beforeTabLeave(activeName,oldName){
                if (oldName==0&&this.addForm.goods_cat.length!==3){
                    this.$message.error('请选择商品分类')
                    return false
                }else {
                    return
                }
            },
            tabClick(){
                if (this.active==1){
                    this.$http.get('categories/'+this.addForm.goods_cat[2]+'/attributes',{params:{sel:'many'}}).then((res)=>{
                        if (res.data.meta.status!==200){
                            this.$message.error('获取数据失败')
                        }else{
                            this.manyTableData=res.data.data
                            this.manyTableData.forEach((item)=>{
                                item.attr_vals=item.attr_vals.length===0? [] : item.attr_vals.split(' ')
                            })
                            
                        }
                    })
                }else if(this.active==2){
                    this.$http.get('categories/'+this.addForm.goods_cat[2]+'/attributes',{params:{sel:'only'}}).then((res)=>{
                        if (res.data.meta.status!==200){
                            this.$message.error('获取数据失败')
                        }else {
                            this.onlyTableData=res.data.data
                            console.log(this.onlyTableData)
                        }
                    })
                }
            },
            //处理预览图片
            handlePreview(res){
                console.log(res)
                this.previewPath=res.response.data.url.replace('127.0.0.1','120.27.246.168')
                this.previewVisible=true                
            },
            //处理移除图片的操作
            handleRemove(file){
                const filePath=file.response.data.tmp_path
                const i=this.addForm.pics.findIndex((x)=>{
                    x.pic===filePath
                })
                this.addForm.pics.splice(i,1)
                console.log(this.addForm)
            },
            //监听图片上传成功事件
            handleSuccess(res){
                //1.拼接得到一个图片信息对象
                const picInfo={pic:res.data.tmp_path}
                this.addForm.pics.push(picInfo)
            },
            //添加商品
            add(){
                this.addForm.goods_introduce=this.addForm.goods_introduce.substring(3,this.addForm.goods_introduce.length-4)
                this.$refs.addFormRef.validate((res)=>{
                    if (!res){
                        this.$message.error('请填写必要的表单项')
                    }else {
                        const form=_.cloneDeep(this.addForm)
                        form.goods_cat=this.addForm.goods_cat.join(',')
                        //处理动态参数
                        this.manyTableData.forEach((item)=>{
                            const newInfo={attr_id:item.attr_id,attr_value:item.attr_vals.join(' ')}
                            this.addForm.attrs.push(newInfo)
                        })
                        //处理静态属性
                        this.onlyTableData.forEach(item=>{
                            const newInfo={attr_id:item.attr_id,attr_value:item.attr_vals}
                            this.addForm.attrs.push(newInfo)
                        })
                        form.attrs=this.addForm.attrs
                        this.$http.post('goods',form).then((res)=>{
                            if (res.data.meta.status==201){
                                this.$message.success('添加商品成功')
                                this.$router.push('/goods')
                            }else {
                                this.$message.error('添加商品失败')
                            }
                        })
                    }
                })
            }
        }
    }
</script>

<style scoped>
.el-checkbox{
    margin: 0 5px 0 0;
}
    .previewImg{
        width: 100%;    
    }
    .btn_add{
        margin-top: 15px;
    }
</style>
